import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Platform,
  StatusBar,
  TouchableOpacity,
  FlatList,
} from "react-native";

const MultiSelect = ({ data, onChangeDatasChoosed }) => {
  const [choosedList, setChoosedList] = useState([]);
  const [customList, setCustomList] = useState([]);
  const [dataList, setDataList] = useState(data);

  useEffect(() => {
    setDataList(data);
  }, [data]);

  useEffect(() => {
    if (dataList) {
      let dataListNow = dataList;
      dataListNow.map((item) => {
        item.checked = false;
      });
      setCustomList(dataListNow);
    }
  }, [dataList]);

  const onPressItem = (id) => {
    let customListNow = [...customList];

    for (const item in customListNow) {
      if (customListNow[item].id === id) {
        if (customListNow[item].checked === false) {
          customListNow[item].checked = true;
          let itemChoosed = customListNow[item];

          setChoosedList([...choosedList, itemChoosed]);
        } else {
          customListNow[item].checked = false;
          let choosedListNow = choosedList.filter((item) => item.id !== id);

          setChoosedList(choosedListNow);
        }
      }
    }
    setCustomList(customListNow);
  };

  useEffect(() => {
    onChangeDatasChoosed(choosedList);
  }, [choosedList]);

  const renderSelectItem = (item, id) => {
    return (
      <View>
        <TouchableOpacity
          style={{
            flexDirection: "row",
            justifyContent: "space-between",
            padding: 10,
            marginVertical: 5,
            backgroundColor: "#fff",
            borderRadius: 5,
            elevation: 4, //设置阴影角度，通过这个设置有无阴影
            shadowOffset: {
              // 设置阴影偏移量
              width: 0,
              height: 4,
            },
            shadowRadius: 4, // 设置阴影模糊半径
            shadowOpacity: 0.1, // 设置阴影的不透明度
            shadowColor: "gray", // 设置阴影色
          }}
          onPress={() => onPressItem(item.item.id)}
        >
          <Text
            style={{
              fontWeight: !item.item.checked ? "400" : "bold",
              fontSize: 15,
              lineHeight: 24,
              color: !item.item.checked ? "#000" : "#3ABEF0",
            }}
          >
            {/* {item.item.id} */}
            {item.item.label}
          </Text>
        </TouchableOpacity>
      </View>
    );
  };

  return (
    <FlatList
      listKey={(item, index) => `multi${index.toString()}`}
      keyExtractor={(item, index) => {
        return index.toString();
      }}
      data={customList}
      renderItem={(item, id) => renderSelectItem(item, id)}
    />
  );
};

var styles = StyleSheet.create({
  container: {
    // marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
    backgroundColor: "white",
  },
});

export default MultiSelect;
